#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import sys
import time
import json
import traceback
import threading

from Ump.common import config
from Ump.common import log
from Ump.utils import ensure_dir,_exec_pipe

from Ump.objs.sync.sync import Sync
from Ump.objs.sync.async import Async
from Ump.objs.sync.license import License
from Ump.objs.sync.kbase import Base
from Ump.objs.session_wrapper import _sw


LOG = log.get_log('Ump.objs.sync.manager')

class SyncManager(Base):

    def __init__(self):
        super(SyncManager, self).__init__()

    def _wrap_sync_all(self, method, cluster_id='ALL', **kwargs):
        '''同步所有的集群，如果没有任何错误方式，msgs为空, 否则非空 '''
        msgs = []
        cluster = _sw.db_cluster(1)
        try:
            msg = method(cluster, **kwargs)
        except Exception, e:
            traceback.print_exc()
            msg = 'Error: sync cluster:%s'%(e)
    
        if not msg == []:
            msgs.append(msg)
        return msgs
    
    def ump_sync(self, cluster_id):
        LOG.info('------------------------')
        LOG.info('ump-sync function %s' % cluster_id)
        LOG.info('------------------------')
        sync = Sync()
        return self._wrap_sync_all(sync._ump_sync_cluster, cluster_id)

    def ump_day_sync(self, cluster_id, is_create=False):
        LOG.info('------------------------')
        LOG.info('ump-day-sync function %s %s' % (cluster_id, is_create))
        LOG.info('------------------------')
        sync = Sync()
        return self._wrap_sync_all(sync._ump_day_sync_cluster, cluster_id, is_create=is_create)
    
    def ump_node_sync(self, body):
        LOG.info('------------------------')
        LOG.info('ump-node-sync function %s' % body)
        LOG.info('------------------------')
        msgs = self._wrap_sync_all(self._ump_node_sync_cluster)

    def ump_async_task(self, body):
        LOG.info('------------------------')
        LOG.info('ump-async-sync function %s' %  body)
        LOG.info('------------------------')
        async = Async()
        msgs = self._wrap_sync_all(async.async_task)

    def ump_sync_task(self, body):
        LOG.info('------------------------')
        LOG.info('ump-task-sync function %s ' %  body)
        LOG.info('------------------------')
        async = Async()
        msgs = self._wrap_sync_all(async.sync_task)

    def ump_license_sync(self, body):
        LOG.info('------------------------')
        LOG.info('ump-license-sync function %s' %  body)
        LOG.info('------------------------')
        license = License()
        msgs = license._ump_license_sync()

    def _ump_node_sync_cluster(self, cluster):
        try:
            self.hom.node_sync()
        except Exception,e:
            traceback.print_exc()
            LOG.info(e)
        return 
